package framework.transport.cluster;

import framework.config.XServiceConfig;
import framework.transport.client.NettyClient;
import framework.transport.codec.XRequest;
import framework.transport.codec.XResponse;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.UUID;

@Slf4j
public class FailFastCluster implements Cluster{


    private NettyClient nettyClient;

    public FailFastCluster(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }

    @Override
    public XResponse<Object> remoteCall(Object proxy, Method method, Object[] args, XServiceConfig xServiceConfig) throws Exception {

        try {
            XRequest request = XRequest.builder().methodName(method.getName())
                    .parameters(args)
                    .interfaceName(method.getDeclaringClass().getName())
                    .paramTypes(method.getParameterTypes())
                    .requestId(UUID.randomUUID().toString())
                    .group(xServiceConfig.getGroup())
                    .version(xServiceConfig.getVersion())
                    .build();
            XResponse<Object> response = nettyClient.sendRequest(request);
            if (response.getCode() != 200) {
                Object data = response.getData();
                if (data instanceof Exception) {
                    throw (Throwable) data;
                }
                throw new RuntimeException(response.getMessage());
            }
            return response;
        } catch (Throwable e) {
            log.error("集群容错策略 FailFast");
            throw (Exception) e;
        }

    }
}
